<template>
  <div class="app">
    <!-- 面包屑导航区域 开始 -->
    <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>查询用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航区域 开始 -->
    <div>
      <!-- 主体开始 -->
      <el-card class="box-card">
        <div>
          <el-select
            class="role"
            v-model="condition.roleId"
            clearable
            placeholder="请选择角色"
          >
            <el-option
              v-for="item in roleList"
              :key="item._id"
              :label="item.roleName"
              :value="item._id"
            >
            </el-option>
          </el-select>
          <el-select
            class="adStatus"
            v-model="condition.adStatus"
            clearable
            placeholder="请选择账户状态"
          >
            <el-option key="0" label="冻结" value="0"> </el-option>
            <el-option key="1" label="正常" value="1"> </el-option>
          </el-select>
          <el-button
            class="addUser el-icon-plus"
            @click="addUser"
            type="success"
            >添加账户</el-button
          >
        </div>
        <el-table v-loading="loading" :data="tableData">
          <el-table-column
            label="用户名"
            prop="adAccount"
            width="180"
          ></el-table-column>
          <el-table-column label="用户密码" prop="adPassword" width="180">
          </el-table-column>
          <el-table-column label="用户状态" width="180">
            <template slot-scope="scope">
              <el-tag :type="scope.row.adStatus == 1 ? 'success' : 'danger'">{{
                scope.row.adStatus == 1 ? '正常' : '冻结'
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="用户角色" width="180" prop="roleName">
            <template slot-scope="scope">
              <div :style="scope.row.roleName ? '' : 'color:#c6ccd1'">
                {{ scope.row.roleName || '无角色' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="角色状态" width="180" prop="">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.roleStatus == 1 ? 'success' : 'danger'"
                >{{ scope.row.roleStatus == 1 ? '正常' : '冻结' }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="my-el-button-default"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                :disabled="
                  user._id == scope.row.uid
                    ? true
                    : false || scope.row.adStatus
                    ? false
                    : true
                "
                @click="handleDelete(scope.$index, scope.row)"
                >冻结</el-button
              >
              <el-button
                size="mini"
                type="danger"
                :disabled="
                  user._id == scope.row.uid
                    ? true
                    : false || scope.row.adStatus
                    ? true
                    : false
                "
                @click="handleTrueDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 开始-->
        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="condition.page"
            :page-sizes="[5, 10, 15, 30]"
            :page-size="condition.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
        <!-- 分页 结束-->
      </el-card>
      <!-- 弹出窗 开始 -->
      <el-dialog
        :title="flag == 1 ? '修改账户信息' : '添加用户'"
        :visible.sync="dialogFormVisible"
        v-loading="formLoading"
      >
        <el-form :rules="rules" ref="ruleForm" :model="form">
          <el-form-item
            label="账户名"
            prop="adAccount"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.adAccount"
              :disabled="flag == 1"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="adPassword"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.adPassword" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            v-if="flag == 1"
            label="状态"
            :label-width="formLabelWidth"
          >
            <el-dropdown @command="updateStatus">
              <el-button
                size="mini"
                :disabled="user._id == form.uid ? true : false"
                :type="form.adStatus == 1 ? 'success' : 'danger'"
              >
                {{ form.adStatus == 1 ? '正常' : '冻结' }}
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="calculation(form, 0)"
                  >冻结</el-dropdown-item
                >
                <el-dropdown-item :command="calculation(form, 1)"
                  >正常</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth">
            <el-dropdown @command="updateRole">
              <el-button class="my-el-button" size="mini" type="primary">
                {{ form.roleName || '请选择角色' }}
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="item in roleList"
                  class="my-el-dropdown-item"
                  :key="item._id"
                  :command="calculation(form, item)"
                  >{{ item.roleName }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="my-el-button-default" @click="dialogFormVisible = false">取 消</el-button>
          <el-button class="my-el-button" type="primary" @click="determine">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  queryUserAll,
  queryRole,
  updateUserById,
  updateUserRoleById,
  queryUser,
  addUser,
  addUserRole,
  queryUserToatl,
  removeUser,
  removeUserRole
} from '@/network/userManager'
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 条件对象
      condition: {
        adStatus: '',
        roleId: '',
        page: 1,
        size: 5
      },
      // 角色列表
      roleList: [],
      value: '',
      // table加载动画
      loading: false,
      user: {},
      // 修改用户信息 弹窗
      dialogFormVisible: false,
      formLabelWidth: '120px',
      // 弹出层表单对象
      form: {
        adAccount: '',
        adPassword: ''
      },
      // 状态  1修改状态 2添加状态
      flag: 1,
      // 表单校验规则
      rules: {
        adAccount: [
          { required: true, message: '请输入账户名', trigger: 'blur' },
          { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
        ],
        adPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 表单加载动画
      formLoading: false,
      total: 0,
      // 选中元素下标
      selectIndex: -1
    }
  },
  methods: {
    // 编辑方法
    handleEdit(index, row) {
      this.flag = 1
      this.selectIndex = index
      console.log(index, row)
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
    },
    // 冻结账户方法
    handleDelete(index, row) {
      if (row.adStatus == 0) {
        return this.$message.warning('该用户已被冻结')
      }
      console.log(index, row)
      this.$confirm('此操作将永久冻结该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          row.adStatus = 0
          this.updateUserById(row)
          this.$message.success('冻结成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消冻结'
          })
        })
    },
    // 修改用户信息
    updateUserById(row) {
      updateUserById({
        _id: row.uid,
        adAccount: row.adAccount,
        adPassword: row.adPassword,
        adStatus: row.adStatus
      })
    },
    // 修改 角色与用户关联的信息
    updateUserRoleById(row) {
      console.info(row)
      updateUserRoleById({
        _id: row._id,
        roleId: row.roleId,
        uid: row.uid
      })
    },
    // 查询 用户信息
    queryUser() {
      this.loading = true
      // 获取 全部用户
      queryUserAll(this.condition).then(res => {
        this.tableData = JSON.parse(res.resp_data).list
        console.info(this.tableData)
        this.loading = false
      })
      // 获取用户 总数
      this.queryUserToatl()
    },
    // 计算函数
    calculation(row, status) {
      return {
        row,
        status
      }
    },
    // 修改用户状态
    updateStatus(item) {
      if (item.status != item.row.adStatus) {
        item.row.adStatus = item.status
      }
      console.info(item)
    },
    // 修改 用户角色
    updateRole(item) {
      console.info(item)
      if (this.flag == 2) {
        this.form.roleId = item.status._id
        this.form.roleName = item.status.roleName
        return
      }
      if (item.status._id != item.row.roleId) {
        item.row.roleId = item.status._id
        if (item.row.roleName == undefined) {
          this.$set(item.row, 'roleName', item.status.roleName)
        } else {
          item.row.roleName = item.status.roleName
        }

        for (let rs in this.roleList) {
          if (this.roleList[rs]._id == item.row.roleId) {
            item.row.roleStatus = this.roleList[rs].roleStatus
          }
        }
      }
    },
    // 添加用户
    addUser() {
      this.flag = 2
      this.dialogFormVisible = true
      this.form = {
        adAccount: '',
        adPassword: '',
        adStatus: 1,
        roleId: '',
        roleName: '',
        roleStatus: 1,
        uid: '',
        _id: ''
      }
    },
    // 确定按钮
    determine() {
      console.info(this.form)
      // 验证表单合格
      this.$refs['ruleForm'].validate(async valid => {
        if (valid) {
          // 添加操作
          if (this.flag == 2) {
            if (!this.form.roleId)
              return this.$message.warning('请为该账户分配角色')
            this.formLoading = true
            let res = await queryUser({ adAccount: this.form.adAccount })
            if (res.data.length > 0) {
              this.formLoading = false
              return this.$message.warning('该用户名已存在')
            }
            let userRes = await addUser(this.form)
            console.info(this.form)
            console.info(userRes)
            this.form.uid = userRes.id_list[0]
            addUserRole(this.form)
            if (this.tableData.length < this.condition.size) {
              // this.form._id=res.id_list[0]
              this.tableData.push(this.form)
            }
            this.queryUserToatl()
            this.formLoading = false
            this.dialogFormVisible = false
            this.$message.success('添加成功')
            return
          }
          // 修改操作
          this.$confirm('此操作将永久修改该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.updateUserById(this.form)
              this.updateUserRoleById(this.form)
              console.info(this.form)
              console.info(this.selectIndex)
              this.tableData.splice(this.selectIndex, 1, this.form)
              this.dialogFormVisible = false
              this.$message.success('修改成功')
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消修改'
              })
            })
        }
      })
    },
    // size数据改变
    handleSizeChange(val) {
      this.condition.size = val
    },
    // 翻页
    handleCurrentChange(val) {
      this.condition.page = val
    },
    // 删除账户
    handleTrueDelete(index, row) {
      this.$confirm('此操作将永久删除该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeUser(row.uid).then(() => {
            this.queryUserToatl()
          })
          removeUserRole(row.uid)
          this.tableData.splice(index, 1)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      console.info(row)
    },
    // 获取 用户总数
    queryUserToatl() {
      queryUserToatl(this.condition).then(res => {
        console.info(res)
        this.total = JSON.parse(res.resp_data).list[0].total
      })
    }
  },
  mounted() {
    let user = sessionStorage.getItem('user')
    this.user = JSON.parse(user)
    this.queryUser()
    queryRole({}).then(res => {
      this.roleList = []
      for (let re in res.data) {
        this.roleList.push(JSON.parse(res.data[re]))
      }
      console.info(this.roleList)
    })
  },
  // 监听查询条件
  watch: {
    'condition.roleId': {
      handler: function() {
        this.queryUser()
      }
    },
    'condition.adStatus': {
      handler: function() {
        this.queryUser()
      }
    },
    'condition.page': {
      // 页码发生变化
      handler: function() {
        this.queryUser()
      }
    },
    'condition.size': {
      // 每页多少条发生变化
      handler: function() {
        this.queryUser()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.role,
.adStatus {
  margin: 0px 4px 8px;
}
.addUser {
  float: right;
}
.addUser::after {
  content: '';
  display: inline-block;
  clear: both;
}
</style>
